const { hospitalModel, docSchedulingModel } = require("../model");
const moment = require("moment"); // 引入moment库来处理日期
function formatDateToYYYYMMDD(dateString) {
  // 创建Date对象
  const date = new Date(dateString);

  // 获取年、月、日部分
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // getMonth()返回的是0-11，所以要+1，并用padStart填充0
  const day = String(date.getDate()).padStart(2, "0"); // getDate()返回的是1-31

  // 拼接成yyyyMMdd格式
  return `${year}${month}${day}`;
}
function getCurrentDate() {  
  const now = new Date();  
  const year = now.getFullYear();  
  const month = String(now.getMonth() + 1).padStart(2, '0'); // getMonth()返回的月份是从0开始的，所以我们需要加1  
  const day = String(now.getDate()).padStart(2, '0'); // getDate()返回的日期可能是一位数，所以我们需要确保它是两位数  

  return `${year}/${month}/${day}`;  
} 
function getCurrentHourMinute() {  
  const now = new Date();  
  const hours = String(now.getHours()).padStart(2, '0');  
  const minutes = String(now.getMinutes()).padStart(2, '0');  

  // 将小时和分钟拼接成一个四位数的字符串，然后转换为数字  
  const hourMinuteNumber = parseInt(`${hours}${minutes}`, 10);  

  return hourMinuteNumber;  
} 
function convertTimeToNumber(timeString) {  
  // 分割字符串获取小时和分钟  
  const [hours, minutes] = timeString.split(':').map(Number);  

  // 确保小时和分钟都是两位数  
  const formattedHours = String(hours).padStart(2, '0');  
  const formattedMinutes = String(minutes).padStart(2, '0');  

  // 拼接小时和分钟，并转换为数字  
  const timeNumber = parseInt(`${formattedHours}${formattedMinutes}`, 10);  

  return timeNumber;  
}  
//获取不同科室下，不同职称的医生列表
exports.getDoctorsWithDepartAndJob = async (req, res) => {
  const { depart, TweDepart, job } = req.body;

  // 判断信息是否详细
  if (depart === undefined || TweDepart === undefined) {
    return res.status(400).json({
      code: 400,
      message: "缺少必要参数",
    });
  }
  //开始查询
  try {
    let result = await hospitalModel
      .find({ depart, TweDepart, job })
      .populate("depart")
      .populate("job");
    res.status(200).json({
      code: 200,
      message: "查询成功",
      data: result,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "查询失败",
      data: error,
    });
  }
};
//给医生添加排班
exports.addDoctorSch = async (req, res) => {
  const {
    doctorId,
    date,
    startTime,
    endTime,
    status,
    maxNumber,
    currentNumber,
    price,
  } = req.body;
  if (
    doctorId === undefined ||
    date === undefined ||
    startTime === undefined ||
    endTime === undefined ||
    status === undefined ||
    maxNumber === undefined
  ) {
    return res.status(400).json({
      code: 400,
      message: "缺少必要参数",
      data: null,
    });
  }
  let isAuyn = await hospitalModel.findOne({_id:doctorId});
  if(isAuyn.isAutonym==2) {
    return res.status(400).json({
      code:400,
      message:"该医生已经离职,无法添加排班",
      data:null
    })
  }
  let nowDate = new Date();
  let dateNumberNow = formatDateToYYYYMMDD(nowDate) * 1;
  const hours24 = String(nowDate.getHours()).padStart(2, "0"); // 24小时制的小时数，不足两位前面补0
  const minutes = String(nowDate.getMinutes()).padStart(2, "0");
  let nowTimeStr = hours24 + minutes;

  if (formatDateToYYYYMMDD(date) * 1 < dateNumberNow) {
    return res.status(400).json({
      code: 400,
      message: "排班日期不能小于当前日期",
      data: null,
    });
  } else {
    if (
      endTime.split(":").join("") * 1 < nowTimeStr * 1 &&
      formatDateToYYYYMMDD(date) * 1 == dateNumberNow
    ) {
      return res.status(400).json({
        code: 400,
        message: "排班结束时间不能小于当前时间",
        data: null,
      });
    }
    if (startTime.split(":").join("") * 1 > endTime.split(":").join("") * 1) {
      return res.status(400).json({
        code: 400,
        message: "排班开始时间不能大于结束时间",
        data: null,
      });
    }
  }
  try {
    let result = await docSchedulingModel.find({
      doctorId,
      date,
      startTime,
      endTime,
    });
    if (result.length > 0) {
      return res.status(400).json({
        code: 400,
        message: "该医生在该时间段已添加排班",
        data: null,
      });
    }
    let dbBack = new docSchedulingModel({
      doctorId,
      date,
      startTime,
      endTime,
      status,
      maxNumber,
      currentNumber: maxNumber,
      price,
    });
    await dbBack.save();
    res.status(200).json({
      code: 200,
      message: "添加成功",
      data: null,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "添加失败",
      data: error,
    });
  }
};
//获取医生排班
// 导出获取医生排班信息的函数
exports.getDoctorSch = async (req, res) => {  
  // 获取医生id
  let doctorId = req.query.id;  
  // 如果医生id为空或格式不正确，返回400
  if (!doctorId ) {  
    return res.status(400).json({  
      code: 400,  
      message: "医生id不能为空或格式不正确",  
      data: null  
    });  
  }  
  // 根据医生id查询医生排班信息，并返回
  let result = await docSchedulingModel.find({doctorId}).populate('doctorId');
  //查找所有date小于今天的排班信息，并更新status为1
  for(let i = 0; i <result.length;i++) {
    if(result[i].date < getCurrentDate()&&result[i].status!=1) {
      result[i].status = 1;
      await docSchedulingModel.updateOne({_id:result[i]._id},{status:1});
    }
  }
  // 过滤出今天排班的信息
  result = result.filter(item=>{
    return item.date == getCurrentDate();
  })
  // 遍历过滤后的排班信息，如果当前时间大于排班结束时间，将状态设置为1，并更新数据库
  for(let i = 0; i <result.length;i++) {
    if(result[i].date == getCurrentDate()) {
      let curnTime = getCurrentHourMinute();
      console.log(curnTime,convertTimeToNumber(result[i].endTime));
      if(curnTime>=convertTimeToNumber(result[i].endTime)) {
        result[i].status = 1;
        await docSchedulingModel.updateOne({_id:result[i]._id},{status:1});
      }
    }
    // 如果当前排班人数为0，将状态设置为2，并更新数据库
    if(result[i].currentNumber == 0) {
      result[i].status = 2;
      await docSchedulingModel.updateOne({_id:result[i]._id},{status:2});
    }
  }
  // 根据医生id查询医生排班信息，并返回
  let result1 = await docSchedulingModel.find({doctorId}).populate('doctorId');
  // 返回200状态码和查询结果
  res.status(200).json({
    code: 200,
    message: "查询成功",
    data: result1,
  })
};
//修改医生排班
exports.updateDoctorSch = async (req, res) => {
  let id = req.query.id;
  const {
    startTime,
    endTime,
    status = 0,
    maxNumber,
    currentNumber,
    price,
    date,
  } = req.body;
  let nowDate = new Date();
  let dateNumberNow = formatDateToYYYYMMDD(nowDate) * 1;
  const hours24 = String(nowDate.getHours()).padStart(2, "0"); // 24小时制的小时数，不足两位前面补0
  const minutes = String(nowDate.getMinutes()).padStart(2, "0");
  let nowTimeStr = hours24 + minutes;
  if (id === undefined) {
    return res.status(400).json({
      code: 400,
      message: "id不能为空",
      data: null,
    });
  }

  if (status === 0) {
    if (formatDateToYYYYMMDD(date) * 1 < dateNumberNow) {
      return res.status(400).json({
        code: 400,
        message: "排班日期不能小于当前日期",
        data: null,
      });
    } else {
      if (
        endTime?.split(":").join("") * 1 < nowTimeStr * 1 &&
        formatDateToYYYYMMDD(date) * 1 < dateNumberNow
      ) {
        return res.status(400).json({
          code: 400,
          message: "排班结束时间不能小于当前时间",
          data: null,
        });
      }
      if (
        startTime?.split(":").join("") * 1 >
        endTime?.split(":").join("") * 1
      ) {
        return res.status(400).json({
          code: 400,
          message: "排班开始时间不能大于结束时间",
          data: null,
        });
      }
    }
    if (currentNumber == 0) {
      return res.status(400).json({
        code: 400,
        message: "人数已满，不能修改状态",
        data: null,
      });
    }
  }
  try {
    let result1 = await docSchedulingModel.findOne({ _id: id });
  
    let count = result1.currentNumber;
    if(result1.maxNumber < maxNumber ) {
      count = count+(maxNumber-result1.maxNumber);
    }else if (result1.maxNumber > maxNumber) {
      count = count-(result1.maxNumber-maxNumber);
    }
    await docSchedulingModel.updateOne(
      { _id: id },
      { startTime, endTime, status, maxNumber, currentNumber:count, price, date }
    );
    res.status(200).json({
      code: 200,
      message: "修改成功",
      data: null,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "修改失败",
      data: error,
    });
  }
};
//获取排班详情
exports.getDoctorSchDetail = async (req, res) => {
  let id = req.query.id;

  if (id==undefined) {
    return res.status(400).json({
      code: 400,
      message: "id不能为空",
      data: null,
    });
  }
  try {
    let result = await docSchedulingModel
      .findOne({ _id: id })
      .populate({
        path: "doctorId",
        model: "Hospital",
        populate: {
          path: "job",
          model: "Job",
        },
      })
    res.status(200).json({
      code: 200,
      message: "查询成功",
      data: result,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "服务器出现问题，请稍后重试",
      data: error,
    });
  }
};
//获取对应科室的所有医生排班
exports.getDoctorSchWithDept = async (req, res) => {
  let { TweDepart } = req.query;
  if(TweDepart==null) {
    return res.status(400).json({
      code: 400,
      message: "科室不能为空",
      data: null,
    })
  }
  try {
    let result = await docSchedulingModel.find().populate('doctorId');
    result = result.filter(item=>{
      return item.date == getCurrentDate();
    })
   for(let i = 0; i <result.length;i++) {
    if(result[i].date == getCurrentDate()) {
      let curnTime = getCurrentHourMinute();
      if(curnTime>=convertTimeToNumber(result[i].endTime)) {
        result[i].status = 1;
        await docSchedulingModel.updateOne({_id:result[i]._id},{status:1});
      }
    }
    if(result[i].currentNumber == 0) {
      result[i].status = 2;
      await docSchedulingModel.updateOne({_id:result[i]._id},{status:2});
    }
   }
    const today = moment();
    const endDate = moment(today).add(5, "days");

    // 判断endDate是否在下一个月
    if (endDate.month() !== today.month()) {
      // 如果endDate在下一个月，设置新的endDate为下个月的对应日期
      const nextMonth = endDate.clone().startOf("month").add(1, "month");
      endDate.date(endDate.date()); // 保留日期的日部分
      endDate.month(nextMonth.month()); // 设置月份为下一个月
      endDate.year(nextMonth.year()); // 设置年份（如果月份变化导致年份也变化）
    } else {
      // 如果endDate还在本月，确保endDate是本月最后一天或指定的日期（取较小值）
      endDate.endOf("month"); // 将endDate设置为本月的最后一天
      if (endDate.isAfter(moment(today).add(5, "days"))) {
        // 如果本月的最后一天超过了指定的5天后，则保持endDate为指定的日期
        endDate.subtract(
          endDate.diff(moment(today).add(5, "days"), "days"),
          "days"
        );
      }
    }

    const todayStr = today.format("YYYY/MM/DD");
    const endDateStr = endDate.format("YYYY/MM/DD");

    let doctorIds = await hospitalModel.distinct("_id", {
      TweDepart: TweDepart,
    });

    if (doctorIds.length === 0) {
      return res.status(404).json({
        code: 404,
        message: "没有找到对应科室的医生",
        data: null,
      });
    }

    const dateRangeQuery = {
      date: { $gte: todayStr, $lte: endDateStr },
      doctorId: { $in: doctorIds }, // 假设这里的字段名已经修正为 "doctorId"
    };
    let result1 = await docSchedulingModel.find(dateRangeQuery).populate({
      path: "doctorId",
      model: "Hospital",
      populate: {
        path: "job",
        model: "Job",
      },
    });

    res.status(200).json({
      code: 200,
      message: "查询成功",
      data: result1,
    });
  } catch (error) {
    console.error("查询排班信息时发生错误:", error); // 记录错误日志
    res.status(500).json({
      code: 500,
      message: "查询失败",
      data: error.message || error, // 提供更具体的错误信息
    });
  }
};
